package com.github.shiqiyue.app.common.utils;


import com.github.shiqiyue.app.common.constants.GlobalConstants;
import com.github.shiqiyue.app.common.entity.TreeNode;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * treeNode工具類
 * @author wenyao.wu
 */
public class TreeNodeUtils {

    /***
     * 维护treeNode的children
     * @param rawTreeNodes
     * @return
     */
    public static List<TreeNode> listToTree(List rawTreeNodes) {
        List<TreeNode> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(rawTreeNodes)) {
            return result;
        }
        Map<Long, TreeNode> map = new HashMap<>(rawTreeNodes.size());
        for (Object object : rawTreeNodes) {
            TreeNode treeNode = (TreeNode) object;
            map.put(treeNode.getId(), treeNode);
        }
        for (Object object : rawTreeNodes) {
            TreeNode treeNode = (TreeNode) object;
            if (treeNode.getPid().equals(GlobalConstants.TREE_TOP_PID)) {
                result.add(treeNode);
                continue;
            }
            TreeNode pNode = map.get(treeNode.getPid());
            if (pNode == null) {
                continue;
            }
            List<TreeNode> children = pNode.getChildren();
            if (CollectionUtils.isEmpty(children)) {
                children = new ArrayList<>();
            }
            children.add(treeNode);
            pNode.setChildren(children);
        }
        return result;
    }
}
